package com.lyt.mall.order.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lyt.common.constant.OrderConstant;
import com.lyt.common.dto.SeckillOrderDTO;
import com.lyt.common.exception.NoStockException;
import com.lyt.common.utils.R;
import com.lyt.common.vo.MemberVO;
import com.lyt.mall.order.dto.OrderCreateDTO;
import com.lyt.mall.order.entity.OrderItemEntity;
import com.lyt.mall.order.feign.CartFeignService;
import com.lyt.mall.order.feign.MemberFeignService;
import com.lyt.mall.order.feign.ProductService;
import com.lyt.mall.order.feign.WareFeignService;
import com.lyt.mall.order.interceptor.AuthInterceptor;
import com.lyt.mall.order.service.OrderItemService;
import com.lyt.mall.order.utils.OrderMsgProducer;
import com.lyt.mall.order.vo.*;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyt.common.utils.PageUtils;
import com.lyt.common.utils.Query;

import com.lyt.mall.order.dao.OrderDao;
import com.lyt.mall.order.entity.OrderEntity;
import com.lyt.mall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    ProductService productService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    OrderMsgProducer orderMsgProducer;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    WareFeignService wareFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取订单确认页中需要获取的相关信息
     * @return
     */
    @Override
    public OrderConfirmVO confirmOrder() {
        OrderConfirmVO vo = new OrderConfirmVO();
        MemberVO memberVO = (MemberVO) AuthInterceptor.threadLocal.get();
        //获取到 RequestContextHolder 的相关信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            //同步主线程中的 RequestContextHolder
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1.查询当前登录用户对应的会员的地址信息
            Long id = memberVO.getId();
            List<MemberAddressVO> addresses = memberFeignService.getAddress(id);
            vo.setAddress(addresses);
        }, executor);
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2.查询购物车中选中的商品信息
            List<OrderItemVO> userCartItems = cartFeignService.getUserCartItems();
            vo.setItems(userCartItems);
        }, executor);
        try {
            CompletableFuture.allOf(future1,future2).get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //3.计算订单的总金额和需要支付的总金额  VO自动计算

        //4.生成防重Token,并存储在Redis中
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_PREFIX + ":" + memberVO.getId(),token);
        //将Token绑定在响应的数据对象中
        vo.setOrderToken(token);
        return vo;
    }

    private Lock lock = new ReentrantLock();

    /**
     * Seata分布式事务管理 需要通过@GlobalTransactional修饰
     * @param vo
     * @return
     * @throws NoStockException
     */
    //@GlobalTransactional
    @Transactional
    @Override
    public OrderResponseVO submitOrder(OrderSubmitVO vo) throws NoStockException{
        //需要返回响应的对象
        OrderResponseVO responseVO = new OrderResponseVO();
        //获取当前登录的用户信息
        MemberVO memberVO = (MemberVO) AuthInterceptor.threadLocal.get();
        //1.验证是否重复提交  保证Redis中的Token的查询和删除是一个原子性操作
        String key = OrderConstant.ORDER_TOKEN_PREFIX + ":" + memberVO.getId();
        String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
                , Arrays.asList(key)
                , vo.getOrderToken());
        if (result == 0){
            //验证失败，说明是重复提交
            responseVO.setCode(1);
            return responseVO;
        }
        //2.创建订单和订单项信息
        OrderCreateDTO orderCreateDTO = createOrder(vo);
        responseVO.setOrderEntity(orderCreateDTO.getOrderEntity());
        //3.保存订单信息
        saveOrder(orderCreateDTO);
        //4.锁定库存信息
        lockWareSkuStock(responseVO, orderCreateDTO);
        //5.同步更新会员的会员积分
        //订单成功后需要给消息中间件发送延迟30s的关单消息
        orderMsgProducer.sendOrderMessage(orderCreateDTO.getOrderEntity().getOrderSN());
        return responseVO;
    }

    @Override
    public PayVO getOrderPay(String orderSn) {
        //根据订单号查询相关的订单信息
        OrderEntity orderEntity = this.getBaseMapper().getOrderByOrderSn(orderSn);
        //通过订单信息封装PayVO对象
        PayVO payVO = new PayVO();
        payVO.setOut_trader_no(orderSn);
        payVO.setTotal_amount(orderEntity.getTotalAmount().setScale(2, RoundingMode.UP).toString());
        //订单名称和订单描述
        payVO.setSubject(orderEntity.getOrderSN());
        payVO.setBody(orderEntity.getOrderSN());
        return payVO;
    }

    /**
     * 更新订单
     * @param orderSn
     */
    @Override
    public void updateOrderStatus(String orderSn,Integer status) {
        this.getBaseMapper().updateOrderStatus(orderSn,status);
    }

    @Override
    public void handleOrderComplete(String orderSn) {
        //1.更新订单状态
        this.updateOrderStatus(orderSn, OrderConstant.OrderStateEnum.TO_SEND_GOODS.getCode());
        //TODO 2.更新库存信息（库存数量递减）

        //TODO 3.购物车中的已经支付的商品移除

        //TODO 4.更新会员积分
    }

    /**
     * 快速完成订单的处理
     * @param orderDTO
     */
    @Transactional
    @Override
    public void quickCreateOrder(SeckillOrderDTO orderDTO) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSN(orderDTO.getOrderSN());
        orderEntity.setStatus(OrderConstant.OrderStateEnum.FOR_THE_PAYMENT.getCode());
        orderEntity.setMemberId(orderDTO.getMemberId());
        orderEntity.setTotalAmount(orderDTO.getSeckillPrice().multiply(new BigDecimal(orderDTO.getNum())));
        this.save(orderEntity);
        OrderItemEntity itemEntity = new OrderItemEntity();
        // TODO 根据SKUID查询对应的SKU信息和SPU信息
        itemEntity.setOrderSN(orderDTO.getOrderSN());
        itemEntity.setSkuPrice(orderDTO.getSeckillPrice());
        itemEntity.setSkuId(orderDTO.getSkuId());
        itemEntity.setRealAmount(orderDTO.getSeckillPrice().multiply(new BigDecimal(orderDTO.getNum())));
        itemEntity.setSkuQuantity(orderDTO.getNum());

        orderItemService.save(itemEntity);
    }

    /**
     * 锁定库存的方法
     * @param responseVO
     * @param orderCreateDTO
     * @throws NoStockException
     */
    private void lockWareSkuStock(OrderResponseVO responseVO, OrderCreateDTO orderCreateDTO) throws NoStockException{
        WareSkuLockVO wareSkuLockVO = new WareSkuLockVO();
        wareSkuLockVO.setOrderSN(orderCreateDTO.getOrderEntity().getOrderSN());
        List<OrderItemVO> orderItemVOS = orderCreateDTO.getOrderItemEntities().stream().map((item) -> {
            OrderItemVO itemVO = new OrderItemVO();
            itemVO.setSkuId(item.getSkuId());
            itemVO.setTitle(item.getSkuName());
            itemVO.setCount(item.getSkuQuantity());
            return itemVO;
        }).collect(Collectors.toList());

        // 远程锁库存的操作
        R r = wareFeignService.orderLockStock(wareSkuLockVO);
        if (r.getCode() == 0){
            //表示锁定库存成功
            responseVO.setCode(0);//表示创建订单成功
        }else{
            //表示锁定库存失败
            responseVO.setCode(2);//表示库存不足，锁定失败
            throw new NoStockException(10000L);
        }
    }

    /**
     * 生成订单数据
     * @param orderCreateDTO
     */
    private void saveOrder(OrderCreateDTO orderCreateDTO) {
        //1.订单数据
        OrderEntity orderEntity = orderCreateDTO.getOrderEntity();
        orderService.save(orderEntity);
        //2.订单项数据
        List<OrderItemEntity> orderItemEntities = orderCreateDTO.getOrderItemEntities();
        orderItemService.saveBatch(orderItemEntities);
    }

    /**
     * 创建订单的方法
     * @param vo
     * @return
     */
    private OrderCreateDTO createOrder(OrderSubmitVO vo) {
        OrderCreateDTO createDTO = new OrderCreateDTO();
        //创建订单
        OrderEntity orderEntity = buildOrder(vo);
        createDTO.setOrderEntity(orderEntity);
        //创建订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderEntity.getOrderSN());
        //根据订单项计算出支付总额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            BigDecimal total = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
            totalAmount = totalAmount.add(total);
        }
        orderEntity.setTotalAmount(totalAmount);
        createDTO.setOrderItemEntities(orderItemEntities);
        return createDTO;
    }

    /**
     * 通过购物车中选中的商品来创建对应的购物项信息
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSN) {
        //创建OrderItemEntity
        List<OrderItemEntity> orderItemEntities = new ArrayList<>();
        //获取购物车中的选中的商品信息
        List<OrderItemVO> userCartItems = cartFeignService.getUserCartItems();
        if (userCartItems != null && userCartItems.size() > 0){
            //统一根据skuId查询出对应的SPU信息
            List<Long> spuIds = new ArrayList<>();
            for (OrderItemVO orderItemVO : userCartItems) {
                if (!spuIds.contains(orderItemVO.getSpuId())){
                    spuIds.add(orderItemVO.getSpuId());
                }
            }
            Long[] spuIdsArray = new Long[spuIds.size()];
            spuIdsArray = spuIds.toArray(spuIdsArray);
            //远程调用商品服务获取到对应的SPU信息
            List<OrderItemSpuInfoVO> spuInfos = productService.getOrderItemSpuInfoBySpuId(spuIdsArray);
            Map<Long, OrderItemSpuInfoVO> map = spuInfos.stream().collect(Collectors.toMap(OrderItemSpuInfoVO::getId, item -> item));
            for (OrderItemVO userCartItem : userCartItems) {
                //获取到商品信息对应的SPU信息
                OrderItemSpuInfoVO spuInfo = map.get(userCartItem.getSpuId());
                OrderItemEntity orderItemEntity = buildOrderItem(userCartItem,spuInfo);
                //绑定对应的订单编号
                orderItemEntity.setOrderSN(orderSN);
                orderItemEntities.add(orderItemEntity);
            }
        }
        return orderItemEntities;
    }

    /**
     * 根据一个购物车中的商品创建对应的 订单项
     * @param userCartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVO userCartItem,OrderItemSpuInfoVO spuInfo) {
        OrderItemEntity entity = new OrderItemEntity();
        //SKU信息
        entity.setSkuId(userCartItem.getSkuId());
        entity.setSkuName(userCartItem.getTitle());
        entity.setSkuPic(userCartItem.getImage());
        entity.setSkuQuantity(userCartItem.getCount());
        List<String> skuAttr = userCartItem.getSkuAttr();
        String skuAttrStr = StringUtils.collectionToDelimitedString(skuAttr, ";");
        entity.setSkuAttrsVals(skuAttrStr);
        //SPU信息
        entity.setSpuId(spuInfo.getId());
        entity.setSpuBrand(spuInfo.getBrandName());
        entity.setCategoryId(spuInfo.getCatalogId());
        entity.setSpuPic(spuInfo.getImg());
        //优惠信息
        //积分信息
        entity.setGiftGrowth(userCartItem.getPrice().intValue());
        entity.setGiftIntegration(userCartItem.getPrice().intValue());
        entity.setSkuPrice(userCartItem.getPrice());
        return entity;
    }

    private OrderEntity buildOrder(OrderSubmitVO vo) {
        //创建OrderEntity
        OrderEntity orderEntity = new OrderEntity();
        //创建订单编号
        String orderSN = IdWorker.getTimeId();
        orderEntity.setOrderSN(orderSN);
        MemberVO memberVO = (MemberVO) AuthInterceptor.threadLocal.get();
        //设置会员相关信息
        orderEntity.setMemberId(memberVO.getId());
        orderEntity.setMemberUsername(memberVO.getUsername());
        //根据收货地址ID获取收货地址的详细信息
        MemberAddressVO memberAddressVO = memberFeignService.getAddressById(vo.getAddrId());
        orderEntity.setReceiverCity(memberAddressVO.getCity());
        orderEntity.setReceiverDetailAddress(memberAddressVO.getDetailAddress());
        orderEntity.setReceiverName(memberAddressVO.getName());
        orderEntity.setReceiverPhone(memberAddressVO.getPhone());
        orderEntity.setReceiverPostCode(memberAddressVO.getPostCode());
        orderEntity.setReceiverRegion(memberAddressVO.getRegion());
        orderEntity.setReceiverProvince(memberAddressVO.getProvince());
        //设置订单状态
        orderEntity.setStatus(OrderConstant.OrderStateEnum.FOR_THE_PAYMENT.getCode());

        return orderEntity;
    }

}